<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import ListApis from '@/apis/list';
import QuestionApis from '@/apis/question';
import useLocalStore from '@/stores/local';
import { computed } from 'vue';
import { getCurrentInstance } from 'vue'
import PaperApis from '@/apis/paper.js'
import { encrypt } from '@/utils/jsencrypt.js'
import {useRoute, useRouter} from "vue-router";
import useUserStore from "@/stores/user.js";
import CommonQuestion from "@/components/common/CommonQuestion.vue";
import NoteApis from "@/apis/note.js";

let exitAction = 'url'
const showLeft = ref(true)
const loading = ref(false)
// 状态显示权重 :当前>标记>(已答|未答)
// const questionStatusList = [{ current: '当前', done: '已答', notDone: '未答', noted: '标记' }]
// 单选多选答案与参考答案对比，其中多选答案排序后循环判断所有或者转字符串对比
// answerStatus:'done','notDone'
// const myAnswerCards = ref([]);
// const anotherMyAnswerCards = ref([]);
// const questionList = ref([])
// const questionTypeMap = ref({})
// const questionMeta = ref({})
// const collapse = ref(['name'])
// const localStore = useLocalStore()

const route = useRoute()
const router = useRouter()
// const userStore = useUserStore()
const qCount = ref(0)
const common=ref(null)


const currentIndex = ref(null)
const questionData = ref(null)
const firstTypeMap = {
  1: 'singleChoice',
  2: 'multipleChoice',
  3: 'judgement',
  4: 'fill',
  5: 'text',
  6: 'combination',
  7: 'indefiniteMultipleChoice'
}
const ccNum=ref(0);
if(route.query.cc){
  ccNum.value=Number(route.query.cc)
}
const currentQuestion = computed(() => {
  if (currentIndex.value) {
    return questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  }
})
// 可为null和{}
const currentOptionsStatus = computed(() => {
  if (currentIndex.value != undefined) {
    let currentCard = questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
    if (currentCard.answerStatus == 'done') {
      // 多选为数组
      let answer = currentCard.lockAnswer;
      // 多选为数组
      let rightAnswer = currentCard.rightAnswer;

      // 判断题选项0、1
      switch (currentCard.firstType) {
        case 1:
        case 3:
          if (answer == rightAnswer) {
            return {
              right: answer,
              wrong: ''
            }
          } else {
            return {
              right: rightAnswer,
              wrong: answer
            }
          }
          break;
          // 多选、不定项
        case 2:
        case 7:
          answer.sort((a, b) => {
            return a.charCodeAt(0) - b.charCodeAt(0)
          });
          answer = answer.toString();
          if (answer == rightAnswer.toString()) {
            return {
              right: rightAnswer,
              wrong: [],
              noSelected: []
            }
          } else {
            let arr1 = answer.split(',')
            let arr2 = [...rightAnswer]
            let right = []
            let wrong = []
            let noSelected = []
            for (let i = 0; i < arr1.length; i++) {
              let findIndex = arr2.findIndex((e) => {
                return e == arr1[i]
              })
              // 正确且选中
              if (findIndex > -1) {
                right.push(arr1[i])
                arr2.splice(findIndex, 1)
              } else {
                wrong.push(arr1[i])
              }
            }
            noSelected.push(...arr2)
            return {
              right,
              wrong,
              noSelected
            }
          }
          break;
        case 4:
          return {}
          break;
        default:
          break;
      }
    }
    return {}
  }
})
async function init(){
   await PaperApis.generateRecords(null, {
    params: {
      industryCode:route.query.industryCode,
      examId:route.query.examId,
      categoryId:route.query.categoryId,
      paperId: route.query.id,
      // recordsId:detail.value.id,
      columnId: route.query.columnId,
      result: false,
      practiceModel: true
    }, headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }).then(res=>{
     // 生成试题集合
     ListApis.questionCollection(encrypt(JSON.stringify({
       collectionType: 'paper',
       industryCode: route.query.industryCode,
       examId:route.query.examId,
       categoryId:route.query.categoryId,
       columnId: route.query.columnId,
       id: res.data.id,
       true: true
     }))).then(res1=>{
       let num = 0
       res1.data.content.forEach(item => {
         item.qs.forEach(e => {
           num++
           if (e.record) {
             // 如果是填空题
             if (e.firstType == 4) {
               let array = e.record.as.split(' ')
               for (let i = 0; i < array.length; i++) {
                 e['answer' + i] = array[i]
               }
               e.answer = e.record.as
               e.lockAnswer = e.record.as;
             } else {
               // 答案是json字符串格式,答案不存在的情况是没做
               if (e.record.as) {
                 e.answer = JSON.parse(e.record.as)
                 e.lockAnswer = JSON.parse(e.record.as);
               }
             }
           } else {
             // 如果是填空题
             if (e.firstType == 4) {
               for (let i = 0; i < e.quOption.length; i++) {
                 e['answer' + i] = ''
                 e.answer = ''
                 e.lockAnswer = ''
               }
             } else {
               e.answer = [1, 3, 5].includes(e.firstType) ? '' : [];
               e.lockAnswer = [1, 3, 5].includes(e.firstType) ? '' : [];
             }

           }
           e.num = num;
           e.current = num == 1;
           e.answerStatus = e.record ? 'done' : 'notDone';
           e.isTrue = e.record ? e.record.rt : false
           e.note = ''
           // e.noted=e.collect

           // 做题时间和收藏时间
           e.time = 0
           if(e.collect){
             if(!route.query.cc){
               ccNum.value++
             }
           }
           e.notedTime = e.collect ? 1 : 0
         })
       })
       questionData.value = res1.data
       currentIndex.value = [0, 0]
       qCount.value = num;
     });
   }).catch ((err)=> {
    if (err.code == 104) {
      exitAction = 'force'
      ElMessage('3秒后返回')
      setTimeout(() => {
        router.go(-1)
      }, 3000)
      return
    }
  })
}
async function submitThis() {
  const currentCard = questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  // 已经提交做了的不能重复提交
  if (currentCard.answerStatus == 'done') {
    return;
  }
  // 提交本题答案请求
  let answer = currentCard.answer;
  if (answer == null || answer == '' || answer.length == 0) {
    ElMessage('请选择答案')
    return;
  }
  if (currentCard.firstType == 4) {
    let arr = [];
    for (let i = 0; i < currentCard.length; i++) {
      arr.push(currentCard['answer' + i].trim())
    }
    currentCard.lockAnswer = arr.join(' ')
  } else {
    currentCard.lockAnswer = currentCard.answer
  }
  let as
  switch (currentCard.firstType) {
    case 1:
    case 3:
    case 5:
      as = answer;
      break;
    case 2:
    case 7:
      as = JSON.stringify(answer)
      break;
    case 4:
      let arr = [];
      for (let i = 0; i < currentCard.quOption.length; i++) {
        arr.push(currentCard['answer' + i].trim())
      }
      as = arr.join(' ')
      break;
    default:

  }
  const requestObj = {
    industryCode:route.query.industryCode,
    examId:route.query.examId,
    categoryId:route.query.categoryId,
    columnId: route.query.columnId,
    qid: currentQuestion.value.id,
    type: firstTypeMap[currentQuestion.value.firstType],
    // type: currentQuestion.value.firstType,
    collectId: questionData.value.id,
    as: answer instanceof Array ? JSON.stringify(answer) : answer,
    answer: currentQuestion.value.answerBase64,
  }
  const res = await QuestionApis.questionCheck(requestObj)
  currentCard.rightAnswer = res.data.as;
  currentCard.time = new Date().getTime();

  currentCard.answerStatus = 'done';
  // 正确
  if (res.data.rt) {
    currentCard.isTrue = true
  } else {
    currentCard.isTrue = false
  }
  questionData.value.lastId = currentQuestion.value.id
}
function changeCurrent(i, j) {
  const [index1, index2] = currentIndex.value
  questionData.value.content[index1].qs[index2].current = false
  questionData.value.content[i].qs[j].current = true
  currentIndex.value = [i, j]
}
function toggle() {
  showLeft.value = !showLeft.value
}
function changeCheckbox(arr) {
  // if (myAnswerCards.value[currentIndex.value].lockAnswer.length > 0) {
  //   return
  // }
  // myAnswerCards.value[currentIndex.value].time = new Date().getTime();
  // lastId = myAnswerCards.value[currentIndex.value].id
}

function changeRadio(val) {
  // if (myAnswerCards.value[currentIndex.value].lockAnswer.length > 0) {
  //   return
  // }
  // myAnswerCards.value[currentIndex.value].time = new Date().getTime()
  // lastId = myAnswerCards.value[currentIndex.value].id
}
function toggleNote() {
  if (!currentQuestion.value.collect) {
    QuestionApis.collectQuestion({
      industryCode:route.query.industryCode,
      examId:route.query.examId,
      categoryId:route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
      true: true,
      recordsType: 'paperRecordChapterPractice',
      data: {
        qt: currentQuestion.value.firstType,
        // qt: firstTypeMap1[currentQuestion.value.firstType],
        tr: '',
        // 章节id为试卷id吗
        cid: route.query.id,
        ct: 'paperRecordChapterPractice',
        cn: route.query.name,
        as: currentQuestion.value.answer,
        sn: currentQuestion.value.sign,
        t: new Date().getTime(),
        st: currentQuestion.value.stem

      }
    }).then(res => {
      if (res.data == true) {
        currentQuestion.value.collect = true
        currentQuestion.value.notedTime = new Date().getTime()
      }
      // QuestionApis.paperRecordsCollect(localStore.userSelectedIdsMap)
    })
  } else {
    QuestionApis.delCollect({
      industryCode:route.query.industryCode,
      examId:route.query.examId,
      categoryId:route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
    }).then(res => {
      if (res.success == true) {
        currentQuestion.value.collect = false
        currentQuestion.value.notedTime = 0
      }
    })
  }
}
function nextQuestion() {
  let current = currentQuestion.value.num
  if (current >= qCount.value) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current + 1) {
        currentIndex.value = [aa, b ]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}
function preQuestion() {
  let current = currentQuestion.value.num
  if (current <= 1) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current - 1) {
        currentIndex.value = [aa, b ]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}
async function saveAndExit() {
  if (loading.value) return;
  loading.value = true;
  // 保存请求
  // 权重lockAnswer>answer，循环一次(lockAnswer/answer)
  // 所有答案填完才能提交
  const commonData = {
    collectId: questionData.value.id,
    recordsType: 'paperRecordChapterPractice',
    industryCode:route.query.industryCode,
    industryId:route.query.industryCode,
    examId:route.query.examId,
    categoryId:route.query.categoryId,}
  ;


  // data1已做，data2收藏，data3错题
  const data1 = {}, data2 = {}, removeIds = [], cdata = {}, data3 = {};

  let sign, dc = 0, ec = 0, cc = 0;

  for (let item of questionData.value.content) {
    for (let q of item.qs) {
      // const cardItem = myAnswerCards.value[i]
      // const questionItem = questionList.value[i]
      let as;
      if (q.firstType == 4) {
        let arr = [];
        for (let i = 0; i < q.quOption.length; i++) {
          if (q['answer' + i]) {
            arr.push(q['answer' + i].trim())
          }
        }
        as = arr.join(' ')
      } else if (q.firstType == 3) {
        as = q.lockAnswer
      } else {
        if(q.lockAnswer instanceof Array){
          as = JSON.stringify(q.lockAnswer)
        }else{
          as = q.lockAnswer
        }
        // as = q.lockAnswer ? JSON.stringify(q.lockAnswer) : q.lockAnswer
      }
      if (q.answerStatus == 'done') {
        // 错题
        if (!q.isTrue) {
          data3[q.id] = {
            qid: q.id,
            qt: q.firstType,
            tr: '',
            as,
            sn: q.sign,
            ct: 'chapter',
            cid: route.query.chapterId,
            cn: route.query.name,
            t: q.time,
            st: q.stem
          }
          ec++;
        }
        dc++;
        data1[q.id] = {
          qid: q.id,
          qt: q.firstType,
          tr: '',
          as,
          sn: q.sign,
          t: q.time,
          rt: q.isTrue,
          newDo: !q.record,
          asb: q.answerBase64
        }
      }

      if (q.collect) {
        cc++;
        cdata[q.id] = q.notedTime
        data2[q.id] = {
          qid: q.id,
          qt: q.firstType,
          tr: '',
          as,
          sn: q.sign,
          ct: 'chapter',
          cid: route.query.chapterId,
          cn: route.query.name,
          t: q.notedTime,
          st: q.stem
        }
      } else {
        if (q.notedTime < 0) {
          removeIds.push(q.id)
        }
      }
    }
  }

  // 相较于上次的数量的增减
  dc -= Number(route.query.dc || 0)
  ec -= Number(route.query.ec || 0)
  cc -= ccNum.value
  let promiseArr = []
  if (questionData.value.lastId) {
    promiseArr.push(QuestionApis.pushChapter(Object.assign({
      collectName: questionData.value.name,
      data: data1, lastId: questionData.value.lastId, totalCount: qCount.value
    }, commonData)))
  }
  promiseArr.push(QuestionApis.saveChapter(Object.assign({data: {dc, ec, cc,}}, commonData)),
      // 取消收藏的是相较于上次的吗
      QuestionApis.pushCollect(Object.assign({collectName: questionData.value.name, removeIds}, commonData, {
        cdata,
        data: data2
      })),
      QuestionApis.pushError({
        ...commonData,

        collectName: questionData.value.name,
        data: data3,
      }))
  return Promise.all(promiseArr).finally(_ => {
    loading.value = false;
    router.go(-1)
  })
}
function doNote(){
//   用el-drawer
  common.value.setDraw(true)
//   获取笔记详情
  NoteApis.getNoteList({
    params:{
      type:'paper',
      relationId:route.query.id,
      questionId:currentQuestion.value.id,
      categoryId:route.query.categoryId,
    }
  }).then(res=>{
    if(res.data.length>0){
      common.value.noteAction='edit'
      common.value.setFormData(res.data[0])
    }else{
      common.value.noteAction='save'
    }
  })
}
function saveNote(formData){
  if(common.value.noteAction=='save'){
    NoteApis.publishNote({
      ...formData,
      type:'paper',
      // 关联id就是章节id之类的
      relationId:route.query.id,
      // verify:'',
      questionId:currentQuestion.value.id,
      categoryId:route.query.categoryId,
    }).then(res=>{
      common.value.setDraw(false)
      ElMessage({
        message:'笔记保存成功',
        type:'success'
      })
    }).catch(_=>{
      ElMessage({
        message:'笔记保存失败',
        type:'error'
      })
    })
  }else{
    NoteApis.updateNote({
      ...formData,
    }).then(res=>{
      common.value.setDraw(false)
      ElMessage({
        message:'笔记更新成功',
        type:'success'
      })
    }).catch(_=>{
      ElMessage({
        message:'笔记更新失败',
        type:'error'
      })
    })
  }


}
init()




</script>

<template>
<div>
  <CommonQuestion ref="common" :qCount="qCount" :submitThis="submitThis" :currentOptionsStatus="currentOptionsStatus"
                  :change-current="changeCurrent"
                  :currentQuestion="currentQuestion"
                  :question-data="questionData" :loading="loading" :toggle="toggle"
                  :show-left="showLeft" :change-checkbox="changeCheckbox" :change-radio="changeRadio"
                  :next-question="nextQuestion" :pre-question="preQuestion" :toggle-note="toggleNote"
                  :save-and-exit="saveAndExit" :do-note="doNote" :save-note="saveNote"/>
</div>
</template>

<style scoped>

</style>